# -*- coding: utf-8 -*-
"""
数据维护管理API

按照模块文档2.3节要求提供数据备份、恢复、清理功能的API接口
"""

from typing import List, Dict, Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query, File, UploadFile
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
import logging

from ....core.database import get_db
from ....auth.jwt_auth import get_current_active_user
from ....services.backup_service import BackupService
from ....services.cleanup_service import CleanupService
from ....services.rbac_service import PermissionDecorator
from ....core.exceptions import ValidationError, BusinessError
from ....core.dto import ResponseDTO

logger = logging.getLogger(__name__)
router = APIRouter()


# ==================== 数据模型 ====================

class BackupCreateRequest(BaseModel):
    """创建备份请求"""
    backup_type: str = Field("full", description="备份类型: full/incremental")
    description: str = Field("", description="备份说明")
    tables: Optional[List[str]] = Field(None, description="指定备份的表")


class RestoreRequest(BaseModel):
    """恢复备份请求"""
    restore_type: str = Field("full", description="恢复类型: full/partial")
    confirm: bool = Field(False, description="确认执行恢复操作")


class CleanupConfigRequest(BaseModel):
    """清理配置请求"""
    rules: Dict[str, Any] = Field(..., description="清理规则配置")


class CleanupExecuteRequest(BaseModel):
    """执行清理请求"""
    cleanup_types: Optional[List[str]] = Field(None, description="指定清理类型")
    dry_run: bool = Field(True, description="是否为试运行")
    confirm: bool = Field(False, description="确认执行清理操作")


# ==================== 数据备份API ====================

@router.post("/backup", response_model=ResponseDTO[Dict], summary="创建数据备份")
@PermissionDecorator.require_permission("system.data_maintenance", "backup")
async def create_backup(
    request: BackupCreateRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """创建数据备份"""
    try:
        backup_service = BackupService(db)
        
        result = await backup_service.create_backup(
            backup_type=request.backup_type,
            description=request.description,
            operator=current_user["username"],
            tables=request.tables
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="备份创建成功",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"创建备份失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建备份失败"
        )


@router.get("/backup/list", response_model=ResponseDTO[Dict], summary="获取备份列表")
@PermissionDecorator.require_permission("system.data_maintenance", "read")
async def get_backup_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    backup_type: Optional[str] = Query(None, description="备份类型筛选"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取备份列表"""
    try:
        backup_service = BackupService(db)
        
        result = backup_service.get_backup_list(
            page=page,
            size=size,
            backup_type=backup_type
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="获取备份列表成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取备份列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取备份列表失败"
        )


@router.delete("/backup/{backup_id}", response_model=ResponseDTO[Dict], summary="删除备份")
@PermissionDecorator.require_permission("system.data_maintenance", "delete")
async def delete_backup(
    backup_id: str,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """删除备份"""
    try:
        backup_service = BackupService(db)
        
        result = await backup_service.delete_backup(
            backup_id=backup_id,
            operator=current_user["username"]
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="备份删除成功",
            data={"backup_id": backup_id, "deleted": result}
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"删除备份失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除备份失败"
        )


@router.post("/backup/cleanup", response_model=ResponseDTO[Dict], summary="清理过期备份")
@PermissionDecorator.require_permission("system.data_maintenance", "manage")
async def cleanup_old_backups(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """清理过期备份"""
    try:
        backup_service = BackupService(db)
        
        result = await backup_service.cleanup_old_backups()
        
        return ResponseDTO[Dict](
            success=True,
            message="过期备份清理完成",
            data=result
        )
        
    except Exception as e:
        logger.error(f"清理过期备份失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="清理过期备份失败"
        )


# ==================== 数据恢复API ====================

@router.post("/backup/{backup_id}/restore", response_model=ResponseDTO[Dict], summary="恢复数据备份")
@PermissionDecorator.require_permission("system.data_maintenance", "restore")
async def restore_backup(
    backup_id: str,
    request: RestoreRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """恢复数据备份"""
    try:
        if not request.confirm:
            raise ValidationError("必须确认执行恢复操作")
        
        backup_service = BackupService(db)
        
        restore_options = {
            "restore_type": request.restore_type
        }
        
        result = await backup_service.restore_backup(
            backup_id=backup_id,
            operator=current_user["username"],
            restore_options=restore_options
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="数据恢复完成",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"恢复备份失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="恢复备份失败"
        )


@router.post("/backup/{backup_id}/validate", response_model=ResponseDTO[Dict], summary="验证备份文件")
@PermissionDecorator.require_permission("system.data_maintenance", "read")
async def validate_backup(
    backup_id: str,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """验证备份文件完整性"""
    try:
        backup_service = BackupService(db)
        
        result = await backup_service.validate_backup(backup_id)
        
        return ResponseDTO[Dict](
            success=True,
            message="备份验证完成",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"验证备份失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="验证备份失败"
        )


@router.get("/restore/history", response_model=ResponseDTO[Dict], summary="获取恢复历史")
@PermissionDecorator.require_permission("system.data_maintenance", "read")
async def get_restore_history(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取恢复历史记录"""
    try:
        backup_service = BackupService(db)
        
        result = backup_service.get_restore_history(page=page, size=size)
        
        return ResponseDTO[Dict](
            success=True,
            message="获取恢复历史成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取恢复历史失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取恢复历史失败"
        )


# ==================== 数据清理API ====================

@router.get("/cleanup/config", response_model=ResponseDTO[Dict], summary="获取清理配置")
@PermissionDecorator.require_permission("system.data_maintenance", "read")
async def get_cleanup_config(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取数据清理配置"""
    try:
        cleanup_service = CleanupService(db)
        
        result = cleanup_service.get_cleanup_config()
        
        return ResponseDTO[Dict](
            success=True,
            message="获取清理配置成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取清理配置失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取清理配置失败"
        )


@router.post("/cleanup/config", response_model=ResponseDTO[Dict], summary="配置清理规则")
@PermissionDecorator.require_permission("system.data_maintenance", "manage")
async def configure_cleanup_rules(
    request: CleanupConfigRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """配置数据清理规则"""
    try:
        cleanup_service = CleanupService(db)
        
        result = await cleanup_service.configure_cleanup_rules(
            rules=request.rules,
            operator=current_user["username"]
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="清理规则配置成功",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"配置清理规则失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="配置清理规则失败"
        )


@router.post("/cleanup/execute", response_model=ResponseDTO[Dict], summary="执行数据清理")
@PermissionDecorator.require_permission("system.data_maintenance", "cleanup")
async def execute_cleanup(
    request: CleanupExecuteRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """执行数据清理"""
    try:
        if not request.dry_run and not request.confirm:
            raise ValidationError("执行实际清理必须确认操作")
        
        cleanup_service = CleanupService(db)
        
        result = await cleanup_service.execute_cleanup(
            cleanup_types=request.cleanup_types,
            dry_run=request.dry_run,
            operator=current_user["username"]
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="数据清理完成" if not request.dry_run else "数据清理预览完成",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"执行数据清理失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="执行数据清理失败"
        )


@router.get("/cleanup/history", response_model=ResponseDTO[Dict], summary="获取清理历史")
@PermissionDecorator.require_permission("system.data_maintenance", "read")
async def get_cleanup_history(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    cleanup_type: Optional[str] = Query(None, description="清理类型筛选"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取数据清理历史记录"""
    try:
        cleanup_service = CleanupService(db)
        
        result = cleanup_service.get_cleanup_history(
            page=page,
            size=size,
            cleanup_type=cleanup_type
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="获取清理历史成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取清理历史失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取清理历史失败"
        )